package com.gmail.hh.flickrj.sample.android.fragments;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.gmail.hh.flickrj.sample.android.FlickrjMainActivity;
import com.gmail.hh.flickrj.sample.android.R;
import com.gmail.hh.flickrj.sample.android.data.DataManagerFlickr;
import com.gmail.hh.flickrj.sample.android.data.PhotoData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData.IPhotolistZoomChanged;
import com.gmail.hh.flickrj.sample.android.images.LazyAdapterPhotolist;
import com.gmail.hh.flickrj.sample.android.interfaces.IDataReadyListener;
import com.gmail.hh.flickrj.sample.android.interfaces.IPhotoSelectedListener;
import com.googlecode.flickrjandroid.people.User;


@SuppressLint("NewApi")
public class FragmentPhotolist extends ListFragment implements
										IPhotolistZoomChanged,
										IDataReadyListener {

	private static final Logger logger = LoggerFactory.getLogger(FragmentPhotolist.class);
	
	public static final String TAG = "fragment_photolist";
	
	private PhotolistData mPhotolistData;
	private LazyAdapterPhotolist mAdapterList;
	private FragmentPhotolist mThis;
	private LinearLayout photolist_container;
	private float previousPhotoListZoomFactor;
	
	// each Activity which uses this Fragment must implement this interface
	private IPhotoSelectedListener mCallbackPhotoSelected;
	private Activity mActivity;


	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
        	mCallbackPhotoSelected = (IPhotoSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement IPhotoSelectedListener");
        }
	}
	

	@Override
	public void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		setRetainInstance(true);
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle data) {
		// Inflate the  layout file.
		View view = inflater.inflate(R.layout.fragment_photolist, null);
		
		this.photolist_container = (LinearLayout) view.findViewById(R.id.photolist_container);
		return view;
	}

	@Override
	public void onViewCreated(View arg0, Bundle arg1) {
		super.onViewCreated(arg0, arg1);  
				
	    // onTouch Listener to the listView (listview is received by a method! )
		// (attention return: 1xfalse, 1xtrue; otherwise no scroll or no zoom!)
		this.getListView().setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				mPhotolistData.applyTouchEvent(FragmentPhotolist.this, event, null);
				// action for changing size of imageView is handled by callback onZoomFactorChanged
				return false;  	// stop propagation true/false
			}
		});
		this.photolist_container.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				mPhotolistData.applyTouchEvent(mThis, event, null);
				// action for changing size of imageView is handled by callback onZoomFactorChanged
				return true;  	// stop propagation true/false
			}
		});

	}
	
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // reload actual Data from DataManager
		if ( !hidden ) {
			boolean forceRefresh = false;
			this.reloadData(forceRefresh);
	    }
    }
    
    @Override
    public void onDestroy() {
		setListAdapter(null);
        super.onDestroy();
    }
	
    // action, when an item of the list is clicked
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		//call activity method (communication with activity)
        PhotoData photoData = mAdapterList.getItem(position);
		mCallbackPhotoSelected.onPhotoSelected(photoData, mPhotolistData,  position,  0l);
	}
	

    
    // refresh (call also be invoked by external classes)
    public void reloadData(boolean forceRefresh) {
    	if (forceRefresh)  {
    	    DataManagerFlickr.getInstance().loadPhotostreamUser(this);
        } else {
    	    onDataReady(true);
        }
    }
	

	// a new/actualized Data-Object is available by DataManager
	@Override
	public void onDataReady(boolean success) {
		if (success) {
			PhotolistData photolistData_old = mPhotolistData;
			mPhotolistData = DataManagerFlickr.getInstance().getPhotolistDataUser();
			// replace only when new versionCounter
			if (mPhotolistData!=null && ( !mPhotolistData.isEqualVersionCounter(photolistData_old) 
					|| mPhotolistData.getPhotolistZoomFactor()!=previousPhotoListZoomFactor ) ) {
				// set Adapter for List-View
				this.createNewAdapter();
	        }
        }
	}
	

	// set Adapter for List-View
	// after zooming the size of the actually viewable images of the list is not changed when no new adapter is created
	public void createNewAdapter() {		
		mAdapterList = new LazyAdapterPhotolist(getActivity(), mPhotolistData );
		mAdapterList.setLayoutResource(LazyAdapterPhotolist.LAYOUT_RESOURCE_LIST);
		setListAdapter(mAdapterList);
		previousPhotoListZoomFactor = mPhotolistData.getPhotolistZoomFactor();   // save last zoomFactor
	}
	
	@Override
	public void onZoomFactorChangedAfterMoved(float zoomFactor) {
		this.createNewAdapter();  // rebuild 
	}
	@Override
	public void onZoomFactorChangedAfterFinished(float zoomFactor) {
		this.createNewAdapter();  // rebuild 
	}


	

}
